package com.eapi.project.controller;

import com.eapi.eapicommom.model.entity.InterfaceInfo;
import com.eapi.eapicommom.model.entity.UserInterfaceInfo;
import com.eapi.project.annotation.AuthCheck;
import com.eapi.project.common.ResultUtils;
import com.eapi.project.common.BaseResponse;
import com.eapi.project.mapper.UserInterfaceInfoMapper;
import com.eapi.project.model.vo.InterfaceInfoVO;
import com.eapi.project.service.InterfaceInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 分析控制器
 */
@Slf4j
@RequestMapping("/analysis")
@RestController
public class AnalysisController {

    @Resource
    private UserInterfaceInfoMapper userInterfaceInfoMapper;

    @Resource
    private InterfaceInfoService interfaceInfoService;

    @GetMapping("/top/interface/invoke")
    @AuthCheck(mustRole = "admin")
    public BaseResponse<List<InterfaceInfoVO>> listTopInvokeInterfaceInfo() {
        List<UserInterfaceInfo> userInterfaceInfoList = userInterfaceInfoMapper.listTopInvokeInterfaceInfo();

        // 分组统计调用次数
        Map<Long, List<UserInterfaceInfo>> interfaceInfoIdObjMap = userInterfaceInfoList.stream()
                .collect(Collectors.groupingBy(UserInterfaceInfo::getInterfaceInfoId));

        // 查询所有接口信息
        List<InterfaceInfo> allInterfaceInfo = interfaceInfoService.list();

        // 构建包含所有接口的InterfaceInfoVO列表，初始化totalNum为0
        Map<Long, InterfaceInfoVO> allInterfaceInfoVOs = allInterfaceInfo.stream()
                .map(info -> {
                    InterfaceInfoVO vo = new InterfaceInfoVO();
                    BeanUtils.copyProperties(info, vo);
                    vo.setTotalNum(0); // 初始化调用次数为0
                    return vo;
                })
                .collect(Collectors.toMap(InterfaceInfoVO::getId, vo -> vo));

        // 更新有调用记录的接口的totalNum
        for (Map.Entry<Long, List<UserInterfaceInfo>> entry : interfaceInfoIdObjMap.entrySet()) {
            Long interfaceId = entry.getKey();
            InterfaceInfoVO vo = allInterfaceInfoVOs.get(interfaceId);
            if (vo != null) {
                vo.setTotalNum(entry.getValue().stream().mapToInt(UserInterfaceInfo::getTotalNum).sum());
            }
        }

        // 转换为列表并返回
        List<InterfaceInfoVO> result = new ArrayList<>(allInterfaceInfoVOs.values());
        return ResultUtils.success(result);
    }
}
